﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using OpenTK.Graphics.OpenGL;
using System.Drawing.Imaging;

namespace PowerOne.GraphicUtilites
{
    public class Texture : IDisposable
        {
            public int GlHandle { get; protected set; }
            public int Width { get; protected set; }
            public int Height { get; protected set; }

            public Texture(Bitmap Bitmap, TextureMinFilter filter = TextureMinFilter.Linear)
            {
                GlHandle = GL.GenTexture();
                Bind();

                Width = Bitmap.Width;
                Height = Bitmap.Height;

                var BitmapData = Bitmap.LockBits(new Rectangle(0, 0, Bitmap.Width, Bitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, BitmapData.Width, BitmapData.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, BitmapData.Scan0);
                Bitmap.UnlockBits(BitmapData);

                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)filter);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)filter);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS,(int)TextureWrapMode.ClampToEdge);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
            }

            public void Bind()
            {
                GL.BindTexture(TextureTarget.Texture2D, GlHandle);
            }

            #region Disposable

            private bool Disposed = false;

            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }

            protected virtual void Dispose(bool Disposing)
            {
                if (!Disposed)
                {
                    if (Disposing)
                    {
                        GL.DeleteTexture(GlHandle);
                    }
                    Disposed = true;
                }
            }

            ~Texture()
            {
                Dispose(false);
            }

            #endregion
        }
}
